<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-28
 * Time: 23:33
 */

namespace app\seller\controller;
use app\common\controller\Seller;
use app\common\model\Withdraw as WithdrawModel;
use app\common\model\Card;
use app\common\model\Member;
use app\common\model\Bank;
class Withdraw extends Seller
{
    public function index()
    {
        return $this->fetch();
    }
    
    public function add(){
        $card = Card::get(['user_id'=>$this->getSellerId()]);
        if(!$card){
            $this->error('请先设置提现信息','/amount/set');
        }
        $seller = Member::get($this->getSellerId());
        $this->assign('max',$seller->cashing_money);//不能超过可提现余额
        $this->assign('banks', Bank::all(['flag' => 1]));
        $this->assign('card',$card);
        return $this->fetch();
    }
    
    public function save(){
        $rule = [
            'user_id|用户id'=>'require',
            'user_card_id|用户提现信息'=>'require',
            'number|提现金额'=>'require'
        ];
        $params = paramForm();
        $params['user_id'] = $this->getSellerId();
        $this->validate($params,$rule);
        
        $seller = Member::get(['id'=>$this->getSellerId()]);
    
        if($seller->cashing_money<(int)$params['number']){
            error('提现金额过大');
        }
    
        if((int)$params['number']<50){
            error('提现金额不能低于50');
        }
    
        $withdraw = new WithdrawModel();
        $rt = $withdraw->allowField(true)->save($params);
    
        //提现申请成功
        if($rt){
        
            //1.Ext表冻结金额增加
            $seller->freeze_money += $params['number'];
            //2.可提现金额减少
            $seller->cashing_money -= $params['number'];
            $rt2 = $seller->isUpdate()->save();
            
            $this->success('发起提现成功','/withdraw');
        }else{
            $this->error('发起提现失败');
        }
        
        
    }
    
}